import {
  loadEnv,
  type ConfigEnv,
  type TerserOptions,
  type UserConfig,
} from 'vite'
import { resolve } from 'path'
import { createVitePlugins } from './build/vite'

// 当前执行node命令时文件夹的地址(工作目录)
const root = process.cwd()

// 路径查找
function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

// https://vite.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
  // 统一使用 mode 参数加载环境变量
  // Vite 会自动按优先级加载：.env.[mode] > .env.local > .env
  const env = loadEnv(mode, root)

  // 解析环境变量，提供默认值
  const VITE_PORT = parseInt(env.VITE_PORT || '80', 10)
  const VITE_OPEN = env.VITE_OPEN === 'true'
  const VITE_BASE_PATH = env.VITE_BASE_PATH || '/'
  const VITE_OUT_DIR = env.VITE_OUT_DIR || 'dist'
  const VITE_DROP_DEBUGGER = env.VITE_DROP_DEBUGGER === 'true'
  const VITE_DROP_CONSOLE = env.VITE_DROP_CONSOLE === 'true'
  const VITE_SOURCEMAP = env.VITE_SOURCEMAP === 'true'

  console.log(`当前环境模式: ${mode}`)
  console.log(`环境变量配置:`, {
    VITE_PORT,
    VITE_OPEN,
    VITE_BASE_PATH,
    VITE_OUT_DIR,
    VITE_DROP_DEBUGGER,
    VITE_DROP_CONSOLE,
    VITE_SOURCEMAP,
  })
  return {
    base: VITE_BASE_PATH,
    root: root,
    // 服务端渲染
    server: {
      port: VITE_PORT, // 端口号
      host: '0.0.0.0',
      open: VITE_OPEN,
      // 本地跨域代理. 目前注释的原因：暂时没有用途，server 端已经支持跨域
      // proxy: {
      //   ['/admin-api']: {
      //     target: env.VITE_BASE_URL,
      //     ws: false,
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(new RegExp(`^/admin-api`), ''),
      //   },
      // },
    },
    // 插件配置
    plugins: createVitePlugins(),

    // 路径别名配置
    resolve: {
      extensions: [
        '.mjs',
        '.js',
        '.ts',
        '.jsx',
        '.tsx',
        '.json',
        '.scss',
        '.css',
      ],
      alias: [
        {
          find: /@\//,
          replacement: `${pathResolve('src')}/`,
        },
      ],
    },
    build: {
      minify: 'terser',
      outDir: VITE_OUT_DIR,
      sourcemap: VITE_SOURCEMAP ? 'inline' : false,
      // brotliSize: false,
      terserOptions: {
        compress: {
          drop_debugger: VITE_DROP_DEBUGGER,
          drop_console: VITE_DROP_CONSOLE,
        },
      } as TerserOptions,
      rollupOptions: {
        output: {
          manualChunks: {
            echarts: ['echarts'], // 将 echarts 单独打包，参考 https://gitee.com/yudaocode/yudao-ui-admin-vue3/issues/IAB1SX 讨论
            'form-create': ['@form-create/element-ui'], // 参考 https://github.com/yudaocode/yudao-ui-admin-vue3/issues/148 讨论
            'form-designer': ['@form-create/designer'],
          },
        },
      },
    },

    // CSS 配置
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/styles/variables.scss" as *;',
        },
      },
    },

    // 环境变量配置
    define: {
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    },

    // 依赖优化
    optimizeDeps: {
      include: ['vue', 'vue-router', 'pinia'],
      exclude: ['@vueuse/core'],
    },
  }
}
